<template>
  <PageWrapper dense contentFullHeight fixedHeight>
    <BasicTable @register="registerTable">
      <template #form-rangeButton="{}">
        <a-space>
          <a-button type="primary" @click="() => handleCycle('prev')">上一周期</a-button>
          <a-button type="primary" @click="() => handleCycle('next')">下一周期</a-button>
        </a-space>
      </template>
      <template #toolbar>
        <a-button type="primary" :disabled="selectedRowData.length === 0" @click="handleRun">
          执行
        </a-button>
      </template>
    </BasicTable>
  </PageWrapper>
</template>
<script setup lang="ts">
import { PageWrapper } from '@/components/Page'
import { BasicTable, useTable } from '@/components/Table'
import dayjs from 'dayjs'
import { searchFormSchema, columns } from './data'
import { getDataCorrectionList, dataCorrectionRecordRun } from '@/api/sys/dataCorrection'
import { onMounted, ref } from 'vue'
import { FormActionType } from '@/components/Form'
import { DataCorrectionTableItem } from '@/api/sys/model/dataCorrection'
import message from '@/views/form-design/utils/message'

defineOptions({ name: 'DataCorrection' })

const selectedRowData = ref<DataCorrectionTableItem[]>([])
let getFormInstance: (() => FormActionType) | null = null
const [registerTable, { getForm }] = useTable({
  title: '数据修正',
  api: getDataCorrectionList,
  columns,
  useSearchForm: true,
  formConfig: {
    labelWidth: 80,
    schemas: searchFormSchema(() => (getFormInstance ? getFormInstance() : getForm())),
    autoSubmitOnEnter: true,
  },
  bordered: true,

  beforeFetch: (params) => {
    // treeId只用来过滤出点位
    delete params.treeId
    if (params.dataTypeId) {
      const {
        dataTypeId: {
          option: { dataTypeId, deviceId },
        },
      } = params
      return {
        ...params,
        dataTypeId: dataTypeId,
        deviceId: deviceId,
      }
    }
    return params
  },
  rowSelection: {
    onChange: (selectedKeys, selectedData) => {
      selectedRowData.value = selectedData
    },
  },
})
onMounted(() => {
  getFormInstance = getForm
})

const handleCycle = (type) => {
  const { measureTimeStart, measureTimeEnd } = getForm().getFieldsValue()
  let start, end
  if (type === 'prev') {
    start = dayjs(measureTimeStart).subtract(1, 'hour')
    end = dayjs(measureTimeEnd).subtract(1, 'hour')
  } else {
    start = dayjs(measureTimeStart).add(1, 'hour')
    end = dayjs(measureTimeEnd).add(1, 'hour')
  }
  getForm().setFieldsValue({
    measureTimeStart: start,
    measureTimeEnd: end,
  })
  getForm().validateFields(['measureTimeStart', 'measureTimeEnd'])
}

const handleRun = () => {
  const { measureTimeStart, measureTimeEnd } = getForm().getFieldsValue()
  const data = selectedRowData.value.map((item) => ({
    dataTypeId: item.dataTypeId,
    deviceId: item.deviceId,
    measureTimeStart,
    measureTimeEnd,
  }))
  dataCorrectionRecordRun(data).then((res) => {
    message.success('执行成功')
  })
}
</script>
